package fr.psm.service.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.transaction.annotation.Transactional;

import fr.psm.bean.Personne;
import fr.psm.service.PersonneService;

@Transactional
public class PersonneServiceImpl implements PersonneService {

	private EntityManager em;

	@PersistenceContext
	public void setEntityManager(EntityManager em) {
		this.em = em;
	}

	@SuppressWarnings("unchecked")
	public List<Personne> findAll() {
		Query query = getEntityManager().createQuery("select p FROM Personne p");
		return query.getResultList();
	}

	public void save(Personne personne) {
		if (personne.getId() == null) {
			// new
			em.persist(personne);
		} else {
			// update
			em.merge(personne);
		}
	}

	public void remove(String id) {
		Personne person = find(id);
		if (person != null) {
			em.remove(person);
		}
	}

	private EntityManager getEntityManager() {
		return em;
	}

	public Personne find(String id) {
		return em.find(Personne.class, id);
	}
}
